<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let obj1 = {
        name: "zhangsan",
        height: 166,
        address: {
          provice: "四川",
          city: "成都",
        },
        say: function () {
          console.log(this.name);
        },
      };
      //   深克隆
      const deep = (obj) => {
        if (obj instanceof Function) {
          // 函数直接返回
          return obj;
        } else if (obj instanceof Array) {
          // 数组遍历并返回新数组
          let newValue = [];
          obj.forEach((item, index) => {
            newValue[index] = deep(item[index]);
          });
          return newValue;
        } else if (obj instanceof Object) {
          // 对象遍历并返回新对象
          let newValue = {};
          for (let i in obj) {
            newValue[i] = deep(obj[i]);
          }
          return newValue;
        } else {
          // 基本类型直接返回
          return obj;
        }
      };
      const obj2 = deep(obj1);
      obj2.name = "ssss";
      obj2.address.city = "资阳";
      obj1.say();
      obj2.say();
      console.log(obj2, obj1);

      //   浅克隆
      const shallow = (obj) => {
        let newValue = {};
        for (let item in obj) {
          console.log(newValue[item], obj[item]);
          newValue[item] = obj[item];
        }
        return newValue;
      };

      const shallowObj = shallow(obj1);
      shallowObj.name = "浅的";
      shallowObj.address.city = "安岳";
      console.log(shallowObj,obj1);
    </script>
  </body>
</html>
